package core.api;

import jade.util.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;

import core.api.performance.PerformanceDescription;
import core.datamodel.Constants;
import core.datamodel.Element;
import core.datamodel.Event;
import core.datamodel.Resource;
import core.datamodel.Usage;
//TODO questa classe va rifatta dove query e specializzazione del sistema di monitoring sono riportate nel ResourceDescription
public class MonitoringData {
	private Logger log = Logger.getJADELogger(this.getClass().getName());
	private Connection conDb = null;

	public MonitoringData (Connection conDb){
		this.conDb= conDb;
	}

	public Usage getUsageResourceElement(Resource resource, Element  element, Date start, long interval) throws SQLException{
		// esegue una query secca al perf indicator value di quaser

		Usage usage = new Usage();

		usage.setElementId(element.getId());
		usage.setStartTime(start);
		usage.setInterval(interval);



		PreparedStatement udata;

		String queryGetUsage="select  min(TIME_VAL) as START_TIME,  AVG(VALUE) as AVG, Max(VALUE) as MAX, " +
		"Min(VALUE) as MIN, sum(VALUE) as SUM, count(*) as TOT_SAMPLE " +
		"from PERF_INDICATOR_VALUE " +
		"where perf_indicator_id=?  and time_val>=? and time_val<? " +
		"group by perf_indicator_id" ;


		//preparo le condizioni 

		if (element.getExternalId()!= 0 ) { // e' definito aggancio al quaser o motore di monitoring
			udata = conDb.prepareStatement(queryGetUsage);
			udata.setLong(1, element.getExternalId());
			udata.setTimestamp(2, new Timestamp(start.getTime()));
			udata.setTimestamp(3, new Timestamp(start.getTime()+ interval));

			System.out.println(" Query con start time pari a :" + new Date(start.getTime()));
			System.out.println(" per external id = "+ element.getExternalId());
			System.out.println(new Timestamp(start.getTime()));

			ResultSet rs = udata.executeQuery();

			while (rs.next()) {
				usage.setAvg(rs.getFloat("AVG"));

				System.out.println(" con risultato "+usage.getAvg());
				usage.setMax(rs.getFloat("MAX"));

				usage.setMin(rs.getFloat("MIN"));
				usage.setSumSample(rs.getFloat("SUM"));
				usage.setNumberSample(rs.getInt("TOT_SAMPLE"));
			}
			rs.close();
			udata.close();

		} else {
			usage = null;
			// devo inizializzare external resource id
			// 
			log.info("Attenzione: sono stati richiesti dati per un con External ID nullo: di element con id ="+ element.getId());
			//getElementExternalID(resource, element);

		}

		return usage;

	}




	public long getElementExternalIdNew ( Resource resource, Element  element)throws SQLException{
		// devo ricostruire l'intercettazione della risorsa.
		PreparedStatement idResource = null;

		// baso tutto sul nome univoco di vm, vlan e dbreplica
		long externlId=0;
		log.info("Inizio la ricerca di externalId per resource name="+resource.getResourceName());

		PerformanceDescription perfDesc = element.getPerformanceDescription();

		if (perfDesc != null ) {

			// query in presenza di vista POC ECN
			String queryResourceId="select usr.*,met.varname,cat.id as CATID, cat.name as CATNAME, met.perf_indicator_id " +
					"from user_view_item usr, resource_category cat," +
					"(select NAME as VARNAME,PERF_INDICATOR_ID, user_view_item_parent_id  " +
					"from user_view_item usr, filter_user_view_item fil where usr.id= fil.USER_VIEW_ITEM_ID and ROOT_ID=1000000	) met " +
					"where usr.id=met.user_view_item_parent_id	" +
					"and usr.category_id=cat.id " +
					"and usr.name=? " +
					"and cat.name=? " +
					"and varname=?";

			idResource = conDb.prepareStatement(queryResourceId);
			idResource.setString(1, resource.getResourceName());
			idResource.setString(2, perfDesc.getPerformanceCategoryName());
			idResource.setString(3, perfDesc.getPerformanceElementName());

			ResultSet rs = idResource.executeQuery();

			if (rs.next()){
				// prendo il perf_indicator_id
				externlId = rs.getLong("PERF_INDICATOR_ID");
				log.info("Ricerca external ID: trovato per element id=" + element.getId() + 
						" name="+element.getName()+" externalId="+externlId);
			} else {
				log.info("Ricerca externalID: nessun perf indicator trovato");
			}
			rs.close();
			idResource.close();

		} else {
			log.info("Ricerca  external ID: nessun performance descriptor associato alla risorsa");
		}


	return externlId;
}

}
